import sys
import os
import traceback
import time
from functools import wraps
from flask import request
from flask import session
from leancloud import Object


def info(content):
    headers = dict(request.headers.items())
    notags = set()
    for t in headers:
        if 'X-Avoscloud' in t:
            notags.add(t)
    for t in notags:
        headers.pop(t)   
    # notags = ['X-Avoscloud-Application-Id', 'X-Avoscloud-Application-Key']
    # for t in notags:
        # headers.pop(t)
        
    headerinfo = '(%s)' % headers
    full_path = request.full_path        
    # sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) 
    # sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)    
    sys.stdout.write('HeaderInfo:%s\nFullPath:%s\n%s\n' % 
        (headerinfo, full_path, content))
    
def error(content):
    headers = dict(request.headers.items())
    notags = set()
    for t in headers:
        if 'X-Avoscloud' in t:
            notags.add(t)
    for t in notags:
        headers.pop(t)
    # notags = ['X-Avoscloud-Application-Id', 'X-Avoscloud-Application-Key']
    # for t in notags:
        # try:
            # headers.pop(t)
        # except KeyError:
            # pass
        
    headerinfo = '(%s)' % headers
    full_path = request.full_path
    # sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) 
    # sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)    
    # sys.stderr.write('HeaderInfo:%s\nFullPath:%s\n%s\n' % 
        # (headerinfo, full_path, content))

        
def log(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
        try:
            return func(*args, **kwargs)
        except Exception as e:
            error(traceback.format_exc())
            raise e
            
    return wrapper
    
def agmlog(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
        try:
            if not os.environ.get('VIRTUAL_ENV', '').startswith('F:'):
                agmlog = Object.extend('Agm_log1')()
                userid = session.get('wechatuserid')
                openid = session.get('openid')
                username = session.get('username')
                if userid:
                    agmlog.set('userid', userid)
                if openid:
                    agmlog.set('openid', openid)
                if username:
                    agmlog.set('username', username)
                agmlog.set('url', request.url).set('method', request.method)
                agmlog.set('useragent', request.user_agent.string).set('ip', request.headers.get('X-Real-Ip', ''))
                referer = request.headers.get('Referer')
                if referer:
                    agmlog.set('referer', referer)
                    import re
                    try:
                        word = re.search(r'&word=([^&]+)', str(referer))
                        if word:
                            import urllib
                            word = urllib.unquote(word.group(1))
                            agmlog.set('word', word)
                    except:
                        error(traceback.format_exc())                        
                agmlog.set('time', int(time.time())).save()
                if request.method == 'POST': 
                    print 'Url:%s|IP:%s|Openid:%s|User-Agent:%s' % (
                        request.url, request.headers.get('X-Real-Ip', ''), (openid or session.get('username')), request.user_agent.string)
        except:
            error(traceback.format_exc())
        return func(*args, **kwargs)
    return wrapper
